(function(angular) {
	'use strict';
	var dependencies = [ 'fs.storage', 'fs.logger', 'fs.router', 'fs.menu', 'fs.validation', 'fs.layout', 'fs.modal', 'oc.lazyLoad', 'ngAnimate',
			'ngResource', 'pascalprecht.translate', 'ui.bootstrap', 'cfp.hotkeys', 'angularFileUpload', 'ui.bootstrap.contextMenu',
			'colorpicker.module', 'angular-clipboard', 'chart.js',
			'ui.grid','ui.grid.autoResize','ui.grid.moveColumns','ui.grid.pagination','ui.grid.resizeColumns','ui.grid.selection','ui.grid.treeBase',
			'ui.grid.treeView','ui.grid.cellNav','ui.grid.emptyBaseLayer','ui.grid.expandable','ui.grid.exporter', 'ui.grid.grouping'];
	angular.module("fs.waf", dependencies).controller("mainController", mainController)
	/*.animation(".fade-in", [ "$animateCss", function($animateCss) {
		return {
			enter : function(element) {
				return $animateCss(element, {
					from : {
						opacity : 0
					},
					to : {
						opacity : 1
					},
					duration : 3
				});
			}
		};
	} ])
	.animation(".fade-out", [ "$animateCss", function($animateCss) {
		return {

			leave : function(element) {
				return $animateCss(element, {
					from : {
						opacity : 1
					},
					to : {
						opacity : 0
					},
					duration : 3
				});
			}
		};
	} ])*/;

	mainController.$inject = [ '$rootScope', '$scope', '$log', '$translate', '$locale', '$location', '$q', '$window', '$document', 'Constants', 'ajaxServiceFactory', 'storageService',
			'signonService', '$ocLazyLoad', 'routerService', 'commonService', '$filter' ];
	function mainController($rootScope, $scope, $log, $translate, $locale, $location, $q, $window, $document, Constants, ajaxServiceFactory, storageService, signonService, $ocLazyLoad,
			routerService, commonService, $filter) {
		var hadBindKeyDown, watcher, ctrl = this, log = $scope.loggerFactory.getLogger("mainController");
		$rootScope.hasBackdrop = function(){
			var backdrop = $document[0].querySelector('.modal-backdrop');
			if (backdrop && !hadBindKeyDown) {
				$document.bind('keydown', function(event) {
					if (event.keyCode == 9) {
						backdrop.focus();
						event.preventDefault();
						event.stopPropagation();
					}
				});
				hadBindKeyDown = true;
			} else if(!backdrop && hadBindKeyDown) {
				$document.unbind('keydown');
				hadBindKeyDown = false;
			}
			return backdrop ? true : false
		}
		angular.element($window).on('resize', function(){
			var header = $document[0].querySelector('.app-header');
			var content = $document[0].querySelector('.app-content');
			var footer = $document[0].querySelector('.app-footer');
			if (header && content && footer) {
				var h = $window.innerHeight -(header.offsetHeight + content.offsetHeight + footer.offsetHeight + 32);
				if (h > 0) {
					angular.element($document[0].querySelector('.app-footer')).css({
						'position' : 'absolute'
					});
				} else if (h <= 0) {
					angular.element($document[0].querySelector('.app-footer')).css({
						'position' : 'relative'
					});
				}
			}
		});
		$scope.$watch(function(){
			var header = $document[0].querySelector('.app-header');
			var content = $document[0].querySelector('.app-content');
			var footer = $document[0].querySelector('.app-footer');
			if (header && content && footer) {
				return $window.innerHeight -(header.offsetHeight + content.offsetHeight + footer.offsetHeight + 32);
			}
		}, function(h){
			if (h > 0) {
				angular.element($document[0].querySelector('.app-footer')).css({
					'position' : 'absolute'
				});
			} else if (h <= 0) {
				angular.element($document[0].querySelector('.app-footer')).css({
					'position' : 'relative'
				});
			}
		});
		ctrl.$onInit = function() {
			initApplicationSetting();
			signonService.isAuthenticated().then(
					function() {
						$rootScope.user = storageService.getUserInfo();
						$rootScope.site = storageService.getSiteInfo();
						$rootScope.menus = storageService.getMenuInfo();
						$rootScope.systemInfo = storageService.getSystemInfo();
						$rootScope.updateTheme();
						$rootScope.initLocaleData();
						//$rootScope.initNotificationData();
						$ocLazyLoad.load(
								[ 
								  'resources/'+ $scope.app.settings.theme +'/nux/css/app.css',
								  'resources/'+ $scope.app.settings.theme +'/nux/css/iconfont.css',
								  'resources/'+ $scope.app.settings.theme + '/nux/js/router/pageRouter.js',
								  'resources/'+ $scope.app.settings.theme + '/nux/js/router/lookupRouter.js',
								  'resources/'+ $scope.app.settings.theme + '/nux/js/router/popupRouter.js', 
								  'resources/'+ $scope.app.settings.theme + '/nux/js/router/routerConfig.js' ]
								, {
									cache : true
								}
						).then(function() {
							if ($location.state()) {
								$scope.go($location.state());
							} else if($location.url()) {
								$scope.go($location.url().substr(1).split('/').join('.'));
							} else {
								$scope.go(Constants.WELCOME_URL);
							}
						}, function(error) {
							log.error(error);
						});
					},
					function() {
						$ocLazyLoad.load(
								[ 'resources/'+ $scope.app.settings.theme +'/nux/css/app.css'], {
									cache : true
								}).then(function() {
									$rootScope.$emit(Constants.NOTIFY_REDIRECT, {
										url : "signon.do"
									});
								}, function(error) {
									log.error(error);
								});
					});
		};
		ctrl.exit = function() {
			signonService.exit().then(function() {
				log.debug('had signoff');
				/*$rootScope.$emit(Constants.NOTIFY_REDIRECT, {
					url : "signon.do"
				});*/
			}, angular.noop);
		};

		watcher = $rootScope.$watch('app', function(settings) {
			storageService.saveSystemSettings(settings);
		}, true);

		$rootScope.$on('$destroy', function() {
			(watcher || angular.noop)();
		});

		function initApplicationSetting() {
			var defaultApp = {
				settings : {
					theme : Constants.THEME_DEFAULT,
					logLevel : $log.logLevels['*']
				}
			};
			$rootScope.app = angular.merge(defaultApp, storageService.getSystemSettings());
		}
		
		$rootScope.initLocaleData = function() {
			var defer = $q.defer();
			var userLocalesAjaxService = ajaxServiceFactory.buildAjaxService({
				getUserLocales : {
					url : 'locales.do',
					method : 'post'
				}
			});
			userLocalesAjaxService.getUserLocales().then(function(response) {
				var systemInfo = storageService.getSystemInfo();
				var language = storageService.getCookie(systemInfo.LOCALE_COOKIE_NAME) || storageService.getUserInfo().locale || $translate.proposedLanguage() || $translate.resolveClientLocale() || 'en_US';
				$scope.langs = {};
				angular.forEach(response.data, function(optionItem, index) {
					$scope.langs[optionItem.value] = optionItem.display;
				});
				$scope.selectLang = $scope.langs[language] || "English";
				$scope.language = language;
				$scope.I18N.language = $scope.langs[language] ? language : 'en_US';
				//storageService.setCookie(systemInfo.LOCALE_COOKIE_NAME, language, 30, false);
				loadCommonResource(language);
				// change page locale
				$scope.setLang = function(language, $event) {
					if ($scope.selectLang != $scope.langs[language]) {
						$scope.language = language;
						$scope.selectLang = $scope.langs[language];
						// java session
						var changeLocaleAjaxService = ajaxServiceFactory.buildAjaxService({
							changeLocale : {
								url : 'changeLocale.do',
								method : 'post'
							}
						});
						changeLocaleAjaxService.changeLocale({"locale" : language}).then(function(response) {
							var stateName = $scope.$state.current.name;
							if (stateName) {
								var url = stateName.split('_');
								if (url.length > 2) {
									url = url.slice(-2);
									url = 'resource/' + url.join('/') + '.do';
								} else {
									url = 'resource/common/home.do';
								}
								var loadResourceAjaxService = ajaxServiceFactory.buildAjaxService({
									loadConfig : {
										'url' : url,
										'method' : 'get'
									}
								});
								loadResourceAjaxService.loadConfig().then(function(response) {
									var resources = response ? response.data : null;
									//storageService.setCookie(systemInfo.LOCALE_COOKIE_NAME, language, 30, false);
									if (resources) {
										storageService.setItemToSession(Constants.SESSION_I18N_RESOURES, resources);
										//storageService.setItemToSession(Constants.SESSION_I18N_VALIDATION_RESOURES, {});
										$rootScope.$emit(Constants.NOTIFY_CHANGE_LANGUAGE, {
											'language' : language
										});
									} else {
										loadCommonResource(language);
									}
								});
								userLocalesAjaxService.getUserLocales().then(function(response) {
									angular.forEach(response.data, function(optionItem, index) {
										$scope.langs[optionItem.value] = optionItem.display;
									});
									$scope.selectLang = $scope.langs[language] || "English";
								});
							}
						});
					}
				};
				defer.resolve();
			}); 
			return defer.promise;
		}
		
		$rootScope.initNotificationData = function() {
			var defer = $q.defer();
			var notificationsAjaxService = ajaxServiceFactory.buildAjaxService({
				getNotifications : {
					url : 'deliMessage/notifications.do',
					method : 'post'
				}
			});
			notificationsAjaxService.getNotifications().then(function(response) {
				$scope.notificationWrap = {};
				$scope.notificationWrap.allNum = response.data.allNum;
				$scope.notificationWrap.notifications = response.data.msgData;
				defer.resolve();
			}); 
			return defer.promise;
		}
		$scope.notificationItemRedirect = function(notification) {
			$scope.go('deliMessage.view', {deliMessageId : notification.deliMessageId, deliveryFolder : 'R'});
		}
		$scope.notificationListRedirect = function() {
			$scope.go('deliMessage.list');
		}

		$rootScope.updateTheme = function() {
			var userInfo = storageService.getUserInfo();
			var theme = userInfo ? (userInfo.themeName || $rootScope.app.settings.theme) : $rootScope.app.settings.theme;
			$rootScope.app.settings.theme =  theme;
			routerService.setTheme(theme);
			updateLogo();
		}
		function updateLogo() {
			commonService.getLogo().then(function(response) {
				$rootScope.logo = response;
			});
		};
		$rootScope.auditAndNoteButtons = [ {
			"name" : "note",
			"enabled" : "!disabledAuditOrNote",
			"tooltip" : "label.note.create",
			"type" : "button",
			"btnClass" : "btn-default",
			"options" : {
				"icon" : "note",
				"callback" : {
					"click" : "createNote"
				}
			},
			'btnScope' : $scope
		},{
			"name" : "audit",
			"enabled" : "!disabledAuditOrNote",
			"tooltip" : "label.audit.viewaudit",
			"type" : "button",
			"btnClass" : "btn-default",
			"options" : {
				"icon" : "audit",
				"callback" : {
					"click" : "viewAudit"
				}
			},
			'btnScope' : $scope
		}];
		
		ctrl.subCompany = {};
		ctrl.filterSubCompany = function() {
			// TODO: filter by $rootScope._subCompany.subCompanyKeyWord
		};
		$rootScope.showSubCompanySelector = false;
		ctrl.layoutConfig = {
			"subCompanyConfig" : {
				"name" : "subCompanyConfig",
				"gridGroups" : [ {
					"grids" : [ "subCompany" ]
				} ],
				"gridConfigs" : {
					"subCompany" : {
						"name" : "subCompany",
						"model" : "companyCode",
						"type" : "customer-select",
						"template" : "company",
						"size" : 12,
						"options" : {
							"hasEmptyOption" : false,
							"filter" : {
								"model" : "subCompanyKeyWord",
								"type" : "text",
								"options" : {
									"callback" : {
										"changed" : "mainCtrl.filterSubCompany"
									}
								},
								"placeholder" : "Filter Key Word"
							},
							"callback" : {
								"changed" : "mainCtrl._subCompanyChanged"
							},
							"data" : 'mainCtrl.subCompanyOption'
						},
						"placeholder" : "Select Company"
					}
				}
			}
		};
		ctrl._subCompanyChanged = function (entity, formCtrl, isInitialized){
			if(isInitialized) {
				return;
			};
			if(ctrl.subCompany && ctrl.subCompany.companyCode) {
				$scope.go("poi.dashboard.panels", ctrl.subCompany);
				$rootScope._subCompany = ctrl.subCompany;
			}
		}
		commonService.getCompanies().then(function(response){
			ctrl.subCompanyOption = response;
			//set default value
			if(response && response.length > 0) {
				ctrl.subCompany.defaultCompanyCode = response[0].value;
				ctrl.subCompany.companyCode = ctrl.subCompany.defaultCompanyCode;
				$rootScope._subCompany = ctrl.subCompany;
			}
		});
		function loadCommonResource(language) {
			ajaxServiceFactory.buildAjaxService({
				loadConfig : {
					'url' : 'resource/common/home.do',
					'method' : 'get'
				}
			}).loadConfig().then(function(response) {
				var resources = response ? response.data : null;
				if (resources) {
					storageService.setItemToSession(Constants.SESSION_I18N_RESOURES, resources);
					//storageService.setItemToSession(Constants.SESSION_I18N_VALIDATION_RESOURES, {});
					$rootScope.$emit(Constants.NOTIFY_CHANGE_LANGUAGE, {
						'language' : language
					});
				}
			});
		}
	}
})(angular);
